/**
 * Created by CJB on 2017-02-17 10:12:41.
 */
strLengthValidator();//验证输入长度
isPhoneValidator();//isPhone:true
autocompleteValidator();//验证自动填充
isEmailValidator();
//邮箱验证
function isEmailValidator(){
  jQuery.validator.addMethod("isEmail", function(value,element) {
      if(value){
          var email = /^[_a-zA-Z0-9\-]+(\.[_a-zA-Z0-9\-]*)*@[a-zA-Z0-9\-]+([\.][a-zA-Z0-9\-]+)+$/;   //邮箱
          return this.optional(element) || (email.test(value));
      }else{
          return true;
      }
  }, "请正确填写邮箱");
}
(function(){
	$(function () {
	    initUpdateWindow();
	    setDefaultStatusRadio("updateUserPhoneTable");
	    initPhoneListSelect();
	    cloneDiv();
	});
	
	
	/**
	 * 初始化已有电话信息类型的默认选择
	 */
	function initPhoneListSelect(){
		$("#phoneTd select").each(function(){
			getDictionaryList($(this).attr("id"), "USER_PHONE", null,$(this).attr("class") );
		});
	};
	/**
	 * 初始化电话的添加删除
	 */
	function cloneDiv(){		
		$("#addPhone").click(function() {  // add为添加div的id
			post(getPath() + "app/dictionary/tree/" + "USER_PHONE",{},
					function(selectResult){	
						var allDivs = $("#phoneTd").find("div");
						var divTest = $("#phoneTd").find("div").last();
						var newDiv = divTest.clone(true);						
						var selectArr = new Array();
						var htmlStr1 = null;
						for(var j = 1; j < selectResult.length; j++){
							var item = selectResult[j];
							var flag = true;
							for(var i = 0; i < allDivs.length; i++){
								var $phoneDiv = $(allDivs[i]);
								var $select0 = $($phoneDiv.find("select")[0]);
								var type = $select0.val();																
									if(type == item.id){																				
										selectArr[i] = item;
										flag = false;
									}															
							}
							if(flag){
								htmlStr1 += "<option value='" + item.id + "'>" + item.name + "</option>";
							}
							} 						
						if(selectArr.length > 0){
							for(var i=0; i < selectArr.length; i++){
								var item = selectArr[i];
								htmlStr1 += "<option value='" + item.id + "'>" + item.name + "</option>";
							}
						}
						
						var $lastDiv = $(divTest);
						var $lastInput = $($lastDiv.find("input")[1]);
						var lastInputId = $lastInput.attr("id");
						var num = lastInputId.substring(5,8);
						
						$(newDiv.find("select")[0]).attr("id",("type"+ (parseInt(num)+1)));
						$(newDiv.find("input")[0]).val("");
						$(newDiv.find("input")[1]).val("");
						
						$(newDiv.find("span")[1]).attr("id",("defaultStatus"+(parseInt(num)+1)))
						if($(newDiv.find("span")[1]).hasClass('selected')){
							$(newDiv.find("span")[1]).removeClass('selected');
						};
						$(newDiv.find("input")[1]).attr("id","phone"+(parseInt(num)+1));
						divTest.after(newDiv);
						//$("#" + selectId).html(htmlStr1);
						//console.log(htmlStr1);
						$(newDiv.find("select")[0]).html(htmlStr1);
					}
			);
	    });
		$(".btn-delete").click(function() { // del为删除input的id			
			if($("#phoneTd").find("div").length > 1)
				$(this).parent().remove();
		});
	
	}
	
	
	
	/**
	 * 初始化更新窗口
	 * @returns {Function}
	 */
	function initUpdateWindow(){
		//初始化时间控件
		initDate("birthday");		
		//初始化字典表
		//getDictionaryList("type", "USER_PHONE", null, null);
	    //声明消息提示
	    var toolTips = new Object();
	
	    //设置表单验证
	    var validator = $("#updateForm").validate({
	    	rules:{
	        	nickname:{
	        		required:true,
	        		strMaxLenth:"255",
	        	},
	        	post:{
	        		strMaxLenth:"255"
	        	},
	        	address:{
	        		strMaxLenth:"255"
	        	},
	        	email:{
	        		isEmail:true
	        	},
	        	deptName:{
	        		autocomplete:["deptName","departmentId"]
	        	},
	        	remark:{
	        		strMaxLenth:"1000",
	        	},
	        	phone:{
	        		isPhone:true
	        	}
	        },
	        messages:{
	            
	        },
	        errorPlacement: function(eror,element){
	            var toolTip = createTooltip(toolTips,element.attr("id"));
	            toolTip.setContent(eror.text());
	            toolTip.close();
	            element.addClass("error-border");
	        },
	        success:function(label){
	            var elementId = label.attr("id").substring(0,label.attr("id").length - 6);
	            var toolTip = toolTips[elementId];
	            $("#" + elementId).removeClass("error-border");
	            toolTip.close();
	            toolTip.detach();
	        },
	        submitHandler:function(form){
	        	//获取电话信息
	        	var phoneDivs = $("#phoneTd").find("div");
	    		var phoneArr = new Array();		
	    		for ( var i = 0; i < phoneDivs.length; i++) {
	    			var $phoneDiv = $(phoneDivs[i]);
	    			var $input0 = $($phoneDiv.find("input")[0]);
	    			var phoneId = $input0.val();
	    			var $select0 = $($phoneDiv.find("select")[0]);
	    			var type = $select0.val();
	    			var $input1 = $($phoneDiv.find("input")[1]);
	    			var phone = $input1.val();
	    			var defaultStatus = 0;
	    			if($($phoneDiv.find("span")[1]).hasClass('selected')){
	    				defaultStatus = 1;
	    			}
	    			if(phoneId !==null&&phoneId!==undefined&&phoneId!==""){
	    					phoneArr.push({"phoneId":phoneId,"type": type,"phone": phone,"defaultStatus":defaultStatus});    				
	    				}else{
	    					phoneArr.push({"type": type,"phone": phone,"defaultStatus":defaultStatus});
	    				}
	    			}
	    		loadDiv.showLoading();
	        	post(getPath() + "base/userPhone/edit/" + $("#id").val(),
	                $("#updateForm").serialize() + "&phones=" + JSON.stringify(phoneArr),
	                function(resultObject){
		                var errors = resultObject.errors;
		                //判断后台是否有返回错误消息
		                if(errors && errors.length > 0){
		                	loadDiv.hideLoading();
		                    for(var i=0; i < errors.length; i++){
		                        var error = errors[i];
		                        var toolTip = createTooltip(toolTips,"update" + error.field);
		                        toolTip.setContent(error.defaultMessage);
		                        $("#update" + error.field).addClass("error-border");
		                    }
		                }else{
		                    //更新成功，弹出添加成功提示框，当用户点击确定后刷新页面
		                	loadDiv.hideLoading();
		                	createWindow("更新成功",{callBack:phoneCallBack}).dialog("open");
		                }
	    		},function(resultObject){
	    			loadDiv.hideLoading();
	        		createWindow(resultObject).dialog('open');
	        	});
	        }
	    });
	    //隐藏列表，显示添加
		$('#dialog').show();
		$('.grid-list').hide();

		//取消
		$('#cancleBtn').click(function(){
			$('#dialog').hide();
			$('.grid-list').show();
		});

		//任务
		setAutoComplete('deptName','departmentId',getPath() + 'org/department/list/select/5',{
			labelField:'name',
			valueField:'id'
		});
	}
})();